<?php

namespace App\Http\Middleware;

use App\Models\Roles;
use Closure;

class AuthenMenus
{

    public function handle($request, Closure $next)
    {
        $current = $request->route()->getName();
        $result = $this->getAccessMenus($current);
        view()->share('active',$result['active']);
        //返回全局权限路由菜单
        view()->share('menus',$result['menus']);
        //返回全局权限路由open
        view()->share('open',$result['open']);
        //返回全局权限
        view()->share('access',$result['access']);
        return $next($request);
    }

    /**
     * 返回权限节点
     * @param $current 当前路由
     * @return array
     */
    protected function getAccessMenus($current)
    {
        $menus = config('menu.manage');
        $access = $menus;
        $open = '';
        $active = '';
        $role = Roles::adminRole();
        foreach($access as $key=>&$menu){
            foreach($menu['node'] as $ke=>&$node){
                //设置菜单开关项
                if($node['url'] == $current){
                    $open = $menu['name'];
                }
                //设置菜单选中项
                if($current == $node['url']){
                    $active = $node['url'];
                }
                foreach($node['child'] as $k=>&$child){
                    if(auth()->user()->role_id>1){
                        //过滤无权限节点
                        if(!in_array($k,$role)){
                            array_pull($node['child'],$k);
                            if(count($node['child']) == 0){
                                array_pull($menu['node'],$ke);
                            }
                        }
                    }
                    if($current == $child['url']){
                        $active = $node['url'];
                        $open = $menu['name'];
                    }
                }
                if(count($menu['node']) == 0){
                    array_pull($access,$key);
                }
            }
        }
//        dump($active); dump($open);
        return ['menus' => $menus, 'open' => $open, 'active' => $active, 'access' => $access];
    }
}
